<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use think\facade\Env;
use think\helper\Str;
use app\model\Bazaar;
use app\model\Zone;
use OSS\OssClient;
use OSS\Core\OssException;
use app\model\Customer;

class Service extends Common
{

	/**
	 * 查询数据
	 *
	 * @return
	 */
	public function read(Request $request) {
		if($this->hasPermission($request->sessInfo, 'service:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');

		array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );

		$platform = $request->param('platform', '', 'trim');
		if($platform) {
			array_push( $where, ['platform', '=',  $platform ] );
		}

		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $where, ['bazaarId', '=',  $bazaarId ] );
		}

		$zoneid = $request->param('zoneid', '', 'trim');
		if($zoneid) {
			array_push( $where, ['zoneid', '=',  $zoneid ] );
		}

		$customerid = $request->param('customerid', '', 'trim');
		if($customerid) {
			array_push( $where, ['customerid', '=',  $customerid ] );
		}

		$status = $request->param('status', '', 'trim');
		if($status === 0 || $status === 1) {
			array_push( $where, ['status', '=',  $status ] );
		}

		$sex = $request->param('sex', '', 'trim');
		if($sex === 0 || $sex === 1) {
			array_push( $where, ['sex', '=',  $sex ] );
		}

		$nickname = $request->param('nickname', '', 'trim');
		if($nickname) {
			array_push( $where, ['nickname', 'like',  "%{$nickname}%" ] );
		}

		$wechat = $request->param('wechat', '', 'trim');
		if($wechat) {
			array_push( $where, ['wechat', 'like',  "%{$wechat}%" ] );
		}

		$name = $request->param('name', '', 'trim');
		if($name) {
			array_push( $where, ['name', 'like',  "%{$name}%" ] );
		}
		
		Db::name('cfg_service')->where('companyId', $request->sessInfo['companyId'])->update(['daycopynumber' => 0]);
		
        $copyItems = Db::query("select count(id) as number, wechat from cfg_copy where companyId = {$request->sessInfo['companyId']} AND to_days(`copyTime`) = to_days(now()) GROUP BY wechat");
		if(is_array($copyItems)) {
			foreach( $copyItems as &$value ) {
				Db::name('cfg_service')->where('companyId', $request->sessInfo['companyId'])->where('wechat', $value['wechat'])->update(['daycopynumber' => $value['number']]);
			}
		}

        $authority = true;
		$authaccount = $this->getWechat($request);
		if($authaccount) {
			array_push( $where, ['id', 'in',  $authaccount ] );
			$authority = false;
		}

		$query = Db::name('cfg_service')->field('id, platform, customerid, bazaarId, zoneid, name, nickname, weight, time, wechat, phone, status, qrcode, sex, number, lasttime, daycopynumber, datetime')->where($where)->order($sort, $order)->paginate($limit);
		$items = $query->items();
		foreach( $items as &$value ) {
			$value['editNumber'] = false;
			$value['newNumber'] = $value['number'];
		}

		return ['code'=> 0, 'msg'=> '', 'count'=> $query->total(), 'data'=> $items,
			'bazaar' => Bazaar::getList($request->sessInfo, false),
			'customer' => Customer::getList($request->sessInfo),
			'authority' => $authority,
			'zone' => Zone::getList($request->sessInfo)
		];
	}

	/**
	 * 更新数据
	 *
	 * @return
	 */
	public function update(Request $request) {
		if($this->hasPermission($request->sessInfo, 'service:update')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$id = $request->param('id', '', 'trim');
		$customerid = $request->param('customerid', '', 'trim');
		$platform = $request->param('platform', '', 'trim');
		$bazaarId = $request->param('bazaarId', '', 'trim');
		$zoneid = $request->param('zoneid', '', 'trim');
		$nickname = $request->param('nickname', '', 'trim');
		$wechat = $request->param('wechat', '', 'trim');
		$phone = $request->param('phone', '', 'trim');
		$status = $request->param('status', '', 'trim');
		$weight = $request->param('weight', '', 'trim');
		$qrcode = $request->param('qrcode', '', 'trim');
		$name = $request->param('name', '', 'trim');
		$time = $request->param('time', '', 'trim');
		$sex = $request->param('sex', '', 'trim');

		$where = [];
		$authaccount = $this->getWechat($request);
		if($authaccount) {
			array_push( $where, ['id', 'in',  $authaccount ] );
		}

		Db::name('cfg_service')->where('id', $id)->where($where)->where('companyId', $request->sessInfo['companyId'])
				->update([ 'platform' => $platform, 'bazaarId' => $bazaarId, 'zoneid' => $zoneid, 'name' => $name, 'time' => $time, 'customerid' => $customerid,
		  'nickname' => $nickname, 'weight' => $weight, 'wechat' => $wechat, 'phone' => $phone, 'status' => $status, 'qrcode' => $qrcode, 'sex' => $sex, 'datetime' => date('Y-m-d H:i:s') ]);
		$this->UpdateGroup($request);
		return ['code'=>0, 'msg'=>'操作成功'];
	}

	/**
	 * 展现操作
	 *
	 * @return
	 */
	public function SetReveal(Request $request) {
		if($this->hasPermission($request->sessInfo, 'service:reveal')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$authaccount = $this->getWechat($request);
		if($authaccount) {
			array_push( $where, ['id', 'in',  $authaccount ] );
		}

		$id = $request->param('id', '', 'trim');
		$newNumber = $request->param('newNumber', '', 'trim');
		Db::name('cfg_service')->where('id', $id)->where($where)->where('companyId', $request->sessInfo['companyId'])
				->update([ 'number' => $newNumber, 'datetime' => date('Y-m-d H:i:s') ]);
		$this->UpdateGroup($request);
		return ['code'=>0, 'msg'=>'操作成功'];
	}

	/**
	 * 更新状态
	 *
	 * @return
	 */
	public function setPause(Request $request) {
		if($this->hasPermission($request->sessInfo, 'service:pause')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$arrayId = [];
		$id = $request->param('id', '', 'trim');
		if( $id ) {
			array_push($arrayId, $id);
		}
		$status = $request->param('status', '', 'trim');
		$selectId = $request->param('selectId', '', 'trim');
		if( is_array($selectId) ) {
			$arrayId = $selectId;
		}

		$where = [];
		$authaccount = $this->getWechat($request);
		if($authaccount) {
			array_push( $where, ['id', 'in',  $authaccount ] );
		}

		Db::name('cfg_service')->where('id', 'in', $arrayId)->where($where)->where('companyId', $request->sessInfo['companyId'])->update(['status' => $status]);
		$this->UpdateGroup($request);
		return ['code'=>0, 'msg'=>'操作成功'];
	}

	/**
	 * 设置客服分组
	 *
	 * @return
	 */
	public function SetGroups(Request $request) {
		if($this->hasPermission($request->sessInfo, 'service:groups')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$arrayId = [];
		$zoneid = $request->param('zoneid', '', 'trim');
		$platform = $request->param('platform', '', 'trim');
		$bazaarId = $request->param('bazaarId', '', 'trim');
		$selectId = $request->param('selectId', '', 'trim');
		if( is_array($selectId) ) {
			$arrayId = $selectId;
		}

		$where = [];
		$authaccount = $this->getWechat($request);
		if($authaccount) {
			array_push( $where, ['id', 'in',  $authaccount ] );
		}

		Db::name('cfg_service')->where('id', 'in', $arrayId)->where($where)->where('companyId', $request->sessInfo['companyId'])->update(['zoneid' => $zoneid, 'platform' => $platform, 'bazaarId' => $bazaarId]);
		$this->UpdateGroup($request);
		return ['code'=>0, 'msg'=>'操作成功'];
	}

	/**
	 * 删除数据
	 *
	 * @return
	 */
	public function delete(Request $request) {
		if($this->hasPermission($request->sessInfo, 'service:delete')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$beginTime = microtime(true);
		$param = $request->param();
		if( !isset($param['id']) ) {
			return ['code'=> 403, 'msg'=> '操作失败!'];
		}

		$where = [];
		$authaccount = $this->getWechat($request);
		if($authaccount) {
			array_push( $where, ['id', 'in',  $authaccount ] );
		}

		$delArray = [];
		$idArray = explode(',', $param['id']);
		if(count($idArray) > 0) {
			foreach( $idArray as $value ) {
				array_push($delArray, Db::table('cfg_service')->where('id', $value)->where($where)->where('companyId', $request->sessInfo['companyId'])->value('wechat'));
				Db::table('cfg_service')->where('companyId', $request->sessInfo['companyId'])->where($where)->where('id', $value)->delete();
			}
			foreach( $delArray as $value ) {
				if( $value ) {
					$endTime = microtime(true);
					$this->cfg_write_oper($request, $request->sessInfo['token'], $request->sessInfo['companyId'], $request->sessInfo['nickname'],
					$request->sessInfo['username'], round($endTime - $beginTime, 3), '客服管理', '删除客服['.$value.']', 0, json_encode($param));
				}
			}
		}
		$this->UpdateGroup($request);
		return ['code'=> 0, 'msg'=> '删除成功!'];
	}

	/**
	 * 创建数据
	 *
	 * @return
	 */
	public function create(Request $request) {
		if($this->hasPermission($request->sessInfo, 'service:save')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$id = $request->param('id', '', 'trim');
		$customerid = $request->param('customerid', '', 'trim');
		$platform = $request->param('platform', '', 'trim');
		$bazaarId = $request->param('bazaarId', '', 'trim');
		$zoneid = $request->param('zoneid', '', 'trim');
		$nickname = $request->param('nickname', '', 'trim');
		$wechat = $request->param('wechat', '', 'trim');
		$phone = $request->param('phone', '', 'trim');
		$status = $request->param('status', '', 'trim');
		$weight = $request->param('weight', '', 'trim');
		$qrcode = $request->param('qrcode', '', 'trim');
		$name = $request->param('name', '', 'trim');
		$time = $request->param('time', '', 'trim');
		$sex = $request->param('sex', '', 'trim');

		$query = Db::table('cfg_service')->where('companyId', $request->sessInfo['companyId'])->where('platform', $platform)
		->where('bazaarId', $bazaarId)->where('zoneid', $zoneid)->where('wechat', $wechat)->value('wechat');
		if(!empty($query)) {
			return ['code'=>403, 'msg'=>'操作失败, 微信已存在!'];
		}

		Db::name('cfg_service')->insert([ 'companyId' => $request->sessInfo['companyId'], 'platform' => $platform, 'customerid' => $customerid, 'bazaarId' => $bazaarId, 'zoneid' => $zoneid, 'name' => $name, 'time' => $time,
		  'weight' => $weight, 'nickname' => $nickname, 'wechat' => $wechat, 'phone' => $phone, 'status' => $status, 'qrcode' => $qrcode, 'sex' => $sex, 'datetime' => date('Y-m-d H:i:s') ]);

    $this->UpdateGroup($request);
		return ['code'=>0, 'msg'=>'操作成功'];
	}

	/**
	 * 上传二维码
	 *
	 * @return
	 */
	public function upload(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'service:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$files = $request->file();
		if (!isset($files['file'])) {
			return json(['code'=> 403, 'msg'=> '上传失败!']);
		}
		if(!is_object($files['file'])) {
			return json(['code'=> 403, 'msg'=> '上传失败!']);
		}
		$object = 'qr' . '/'. sha1( $request->sessInfo['companyId'] . microtime(true) ) . '.' . $files['file']->getOriginalExtension();
		$array = $this->uploadFile($object, $files['file']->getPathName());
		return json($array);
	}

	/**
	 * 上传方法
	 *
	 * @return
	 */
	protected function uploadFile($object, $filePath)	{
		$result = ['code'=> 403, 'msg'=> '上传失败!'];
		if (file_exists($filePath) == false) {
			return $result;
		}
		$bucket = Env::get('aliyun.bucket', 'bucket');
		if ($bucket == 'bucket') {
			return $result;
		}
		$endpoint = Env::get('aliyun.endpoint', 'endpoint');
		if ($endpoint == 'endpoint') {
			return $result;
		}
		$accessKeyId = Env::get('aliyun.accesskeyid', 'accesskeyid');
		if ($accessKeyId == 'accessKeyId') {
			return $result;
		}
		$accessKeySecret = Env::get('aliyun.accesskeysecret', 'accesskeysecret');
		if ($accessKeySecret == 'accessKeySecret') {
			return $result;
		}
		$originaldomain = Env::get('aliyun.originaldomain', 'originaldomain');
		if ($originaldomain == 'originaldomain') {
			return $result;
		}
		$domain = Env::get('aliyun.domain', 'domain');
		if ($domain == 'domain') {
			return $result;
		}
		try {
			$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
			$result = $ossClient->uploadFile($bucket, $object, $filePath);
			if (isset($result['info']['http_code']) && $result['info']['http_code'] == 200) {
				$result = ['code'=> 0, 'msg'=> '上传成功!', 'url' => str_replace($originaldomain, $domain, $result['info']['url'])];
			}
		} catch (OssException $e) {
			$result = ['code'=> 403, 'msg'=>$e->getMessage()];
		}
		return $result;
	}

	protected function getWechat($request)	{
		$roleId = Db::table('cfg_user')->where('id', $request->sessInfo['id'])->value('role');
		if(empty($roleId)) {
			return false;
		}
		$query = Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])->where('id', $roleId)->value('authwechat');
		if(empty($query)) {
			return false;
		}
		return $query;
	}


	protected function UpdateGroup($request)	{
		$zoneArray = Db::table('cfg_zone')->field('id')->where('companyId', $request->sessInfo['companyId'])->select()->toArray();
		if(is_array($zoneArray)) {
			foreach($zoneArray as $value) {
				$servicArray = Db::table('cfg_service')->field('id, name, nickname, wechat')->where('zoneid', $value['id'])->select()->toArray();
				if(is_array($servicArray)) {
					$service = serialize($servicArray);
					Db::name('cfg_zone')->where('id', $value['id'])->update(['service' => $service]);
				}
			}
		}
	}

}
